package com.tinem.platform.web.auth.login.oauth2.ext;

import com.tinem.platform.module.pojo.co.SessionKeyEnum;
import com.tinem.platform.module.starter.web.context.GatewayContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class OAuth2AuthenticationFilter extends AbstractAuthenticationProcessingFilter {

	private static final String LOGIN_PROCESSING = "/endpoint/oauth2/login.do";

	public OAuth2AuthenticationFilter() {
        super(new AntPathRequestMatcher(LOGIN_PROCESSING, "GET"));
    }

	@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException {
		try {
			GatewayContext.REQUEST_LOCAL.set(request);
			GatewayContext.RESPONSE_LOCAL.set(response);
			OAuth2AuthenticationToken authRequest = (OAuth2AuthenticationToken) request.getSession().getAttribute(SessionKeyEnum.oauth2_token.getKey());
			// Allow subclasses to set the "details" property
			setDetails(request, authRequest);
			Authentication authentication =  this.getAuthenticationManager().authenticate(authRequest);
			return authentication;
		}finally {
			GatewayContext.RESPONSE_LOCAL.remove();
			GatewayContext.REQUEST_LOCAL.remove();
		}

	}

	protected void setDetails(HttpServletRequest request, OAuth2AuthenticationToken authRequest) {
		authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
	}

}